<?php
session_start();

$_SESSION["errmsg"] = '';
require_once '../include/config.lib.php';
require_once '../include/database.lib.php';

ConnectToDB();// Connect to the DB.

$password = strtoupper(SHA1($_POST["password"]));//encrypt password by SHA1 and upper case.
$authenticationReq = DBExecute("SELECT id, username FROM person WHERE username = ? AND password = ?",array($_POST["accountNo"],$password));
$authentication = $authenticationReq->fetchAssocRow();

$url = $_SESSION["previouspage"];

$_SESSION["accountNo"] = $authentication["USERNAME"];
$_SESSION["personid"] = $authentication["ID"];
if(isset($_SESSION["accountNo"]))
{//user name and password correct
	$today = date("Y-m-d");
	$beforetoday = strtotime("-5 day");
	$beforetoday = date("Y-m-d", $beforetoday);
	
	$personReq = DBExecute('SELECT * FROM person AS p, (
														SELECT COUNT(DISTINCT authoringbib.bibtexid) AS authorcount FROM authoringbib WHERE authoringbib.personid=?
													) AS a, (
														SELECT COUNT(DISTINCT reading.resourceid) AS readingcount FROM reading WHERE reading.personid=?
													) AS r, (
														SELECT COUNT(DISTINCT annotation.resourceid) AS reviewcount, COUNT(*) AS commentcount FROM annotation WHERE personid=?
													) AS c WHERE p.id=?', array($authentication['ID'], $authentication['ID'], $authentication['ID'], $authentication['ID']));
	$person = $personReq->fetchAssocRow();
	
	if($person['LATESTACTIVITY'] != null && $person['LATESTACTIVITY'] >= $beforetoday && $today != $person['LASTLOGIN'])
	{//if the person's lastactivity is in five days before today, bonus will be added
		DBExecute("UPDATE DB2INST1.person SET logintimes = logintimes+1, LASTLOGIN = ? WHERE ID = ?",array($today,$authentication['ID']));
	}
	else if($today != $person['LASTLOGIN'])
	{
		//else only update last log in time
		DBExecute("UPDATE DB2INST1.person SET LASTLOGIN = ? WHERE ID = ?",array($today,$authentication['ID']));
	}
	else
	{
	}
	
	echo "<HTML><META http-equiv=\"refresh\" content=\"0; url='".$url."'\"></HTML>";//redirect to the previous page
}
else 
{//password or user name wrong
	$_SESSION["errmsg"] = "Wrong user name or password.";
	echo "<HTML><META http-equiv=\"refresh\" content=\"0; url=../login.php\"></HTML>";//redirect to the login page
}
?>